Java Multidimensional Arrays

A multi-dimensional array is an array of arrays. So each element in the multidimensional array is an array itself.

Example

int[][] x = new x[3][3];

Here, the variable x is a 2-dimensional array which will contain 3 rows and 3 columns.

Initializing 2D array

We can assign values to an array initially during the declaration itself.

Example

int[][] x = {{1,2,3},{4,5,6},{7,8,9}};

Accessing the value of the array

In order to access the value of the array we need to provide the row index and the column index position.

Example

int[][] x = {{1,2,3},{4,5,6},{7,8,9}};
System.out.println(x[1][1]);  // 5

Example to print all elements in 2D array

class Main {
    public static void main(String[] args) {

        int[][] x = {{1,2,3},{4,5,6},{7,8,9}};
      
        for (int i = 0; i < x.length; ++i) {
            for(int j = 0; j < x[i].length; ++j) {
                System.out.print(x[i][j]+" ");
            }
            System.out.println();
        }
    }
}

Output

1 2 3 
4 5 6 
7 8 9 

In the above program, we have initialized an 2D array in x variable.

Next, we use first for loop to loop through the rows and the second for loop to loop through the columns.

Inside the second for loop block, we will print the value particular row and column.

At the end of first for loop we use System.out.println() to move to the next line for printing the next row values.


Most Read